import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Swiper, Image, Avatar, Toast, DotLoading, ImageViewer, Button } from 'antd-mobile';
import { HeartOutline, HeartFill, MessageOutline, UploadOutline, LeftOutline } from 'antd-mobile-icons';
import { getTravelDetail, TravelItem, likeTravel, unlikeTravel, shareTravel } from '../../services/api';
import { Comments } from './components/Comments';
import './styles.css';

interface TravelDetail extends TravelItem {
  isLiked: boolean;
  likeCount: number;
  commentCount: number;
  shareCount: number;
}

const TravelDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [travel, setTravel] = useState<TravelDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [imageViewerVisible, setImageViewerVisible] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [isFollowing, setIsFollowing] = useState(false);
  const [showComments, setShowComments] = useState(false);

  useEffect(() => {
    const fetchTravelDetail = async () => {
      try {
        setLoading(true);
        setError(null);
        const data = await getTravelDetail(id!);

        console.log('接口返回数据:', data);

        const detail = data?.data; // 这里取 data.data

        if (detail) {
          setTravel({
            id: detail.id || detail._id,
            title: detail.title || '无标题',
            content: detail.content || '无内容',
            images: Array.isArray(detail.images) ? detail.images : [],
            createdAt: detail.createdAt || new Date().toISOString(),
            location: detail.location || '未知位置',
            author: {
              avatar: detail.author?.avatar || '',
              nickname: detail.author?.nickname || '未知作者'
            },
            isLiked: false,
            likeCount: Math.floor(Math.random() * 100),
            commentCount: Math.floor(Math.random() * 50),
            shareCount: Math.floor(Math.random() * 30),
          });
        } else {
          throw new Error('获取数据失败');
        }
      } catch (err) {
        console.error('获取游记详情失败:', err);
        setError('获取游记详情失败，请稍后重试');
        Toast.show({
          icon: 'fail',
          content: '获取游记详情失败，请稍后重试',
        });
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchTravelDetail();
    }
  }, [id]);

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  };

  const handleImageClick = (index: number) => {
    setCurrentImageIndex(index);
    setImageViewerVisible(true);
  };

  const [isLiked, setIsLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(11);
  const [shareCount, setShareCount] = useState(7);

  const handleLike = () => {
    setIsLiked(v => !v);
    setLikeCount(c => isLiked ? c - 1 : c + 1);
  };
  const handleShare = () => {
    setShareCount(c => c + 1);
    Toast.show({ content: '分享功能仅为演示', position: 'bottom' });
  };
  const handleFollow = () => {
    setIsFollowing(!isFollowing);
    Toast.show({
      content: isFollowing ? '已取消关注' : '已关注',
      position: 'bottom',
    });
  };

  const handleBack = () => {
    navigate(-1);
  };

  const handleComment = () => {
    setShowComments(true);
  };

  const handleSubmitComment = async (content: string) => {
    // TODO: 实现评论提交逻辑
    await new Promise(resolve => setTimeout(resolve, 1000));
  };

  if (loading) {
    return (
      <div className="loading-container">
        <span>加载中</span>
        <DotLoading />
      </div>
    );
  }

  if (error || !travel) {
    return (
      <div className="error-container">
        {error || '游记不存在'}
      </div>
    );
  }

  return (
    <div className="travel-detail">
      <div className="travel-header">
        <div className="back-button" onClick={handleBack}>
          <LeftOutline />
        </div>
        <h1 className="travel-title">{travel.title}</h1>
        <div className="travel-author">
          {travel.author ? (
            <>
              <Avatar src={travel.author.avatar} style={{ '--size': '36px' }} />
              <div className="travel-author-info">
                <div className="travel-author-name">{travel.author.nickname}</div>
                <div className="travel-meta">
                  <span className="travel-meta-item">{formatDate(travel.createdAt)}</span>
                  <span className="travel-meta-item">{travel.location}</span>
                </div>
              </div>
              <Button
                className={`follow-button ${isFollowing ? 'following' : ''}`}
                onClick={handleFollow}
              >
                {isFollowing ? '已关注' : '+ 关注'}
              </Button>
            </>
          ) : (
            <div>作者信息不可用</div>
          )}
        </div>
      </div>

      <div className="travel-images">
        <Swiper>
          {travel.images && Array.isArray(travel.images) ? travel.images.map((image, index) => (
            <Swiper.Item key={index}>
              <Image
                src={image}
                fit="cover"
                className="travel-image"
                onClick={() => handleImageClick(index)}
              />
            </Swiper.Item>
          )) : <Swiper.Item><div className="no-images">暂无图片</div></Swiper.Item>}
        </Swiper>
      </div>

      <div className="travel-content">{travel.content}</div>

      {showComments && (
        <Comments
          travelId={travel.id}
          comments={[]}
          onSubmitComment={handleSubmitComment}
        />
      )}

      <div className="travel-actions-fixed">
        <div className="travel-action-btn" onClick={handleLike}>
          {isLiked ? <HeartFill color="red" /> : <HeartOutline />}
          <span>{likeCount}</span>
        </div>
        <div className="travel-action-btn" onClick={handleShare}>
          <UploadOutline />
          <span>{shareCount}</span>
        </div>
        <div className="travel-action-btn" onClick={handleComment}>
          <MessageOutline />
          <span>评论</span>
        </div>
      </div>

      <ImageViewer
        image={travel.images && Array.isArray(travel.images) && travel.images.length > 0 ? travel.images[currentImageIndex] : ''}
        visible={imageViewerVisible}
        onClose={() => setImageViewerVisible(false)}
      />
    </div>
  );
};

export default TravelDetailPage;
